<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeSearch"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="detps"
          :props="defalutProps"
          :default-expand-all="true"
          :default-expand-keys="id"
          :highlight-current="true"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <div class="right-top">
          <el-breadcrumb separator=">">
            <el-breadcrumb-item :to="{ path: '/' }">传智教育</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">活动管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>活动列表</el-breadcrumb-item>
          </el-breadcrumb>
          <el-row class="opeate-tools" type="flex" justify="end">
            <el-button v-permission="'add-emploayee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
            <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
            <el-button size="mini" @click="exportTable">excel导出</el-button>
          </el-row>
        </div>
        <!-- 表格组件 -->
        <el-table v-loading="isLoading" :data="list">
          <el-table-column class="userPhoto" porp="staffPhoto" label="头像" align="center">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" shape="square" size="small" :src="row.staffPhoto" />
              <span v-else style="display: inline-block;padding: 2px 7px;border-radius: 4px;border: 1px solid #e3e3e3;">
                {{ row.username?.charAt(0) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable align="center" />
          <el-table-column prop="workNumber" label="工号" sortable align="center" />
          <el-table-column label="聘用形式" align="center">
            <template v-slot="{ row }">
              <span>{{ row.formOfEmployment === 1 ? '正式' : '非正式' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" align="center" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable align="center" />
          <el-table-column label="操作" width="150px" align="center">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">编辑</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                :title="`是否删除员工${ row.username }`"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px;" align="middle" type="flex" justify="center">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <!-- 导入组件 -->
    <ImportTable :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!-- 弹窗组件 -->
    <el-dialog
      :visible.sync="showRoleDialog"
      title="分配角色"
    >
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="btnRoleOk">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { ListToTree } from '@/utils'
import { getEmplayee, exportEmplayee, delEmployee, getRoleList, getEmplayeeDetail, assignRole } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportTable from './components/importTable.vue'

export default {
  name: 'Employee',
  components: {
    ImportTable
  },
  data() {
    return {
      // 组织数据
      detps: [],
      defalutProps: {
        label: 'name',
        children: 'children'
      },
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      // 角色数据
      roleList: [],
      // 双向绑定
      roleIds: [],
      // 员工列表
      list: [],
      total: 0,
      // 加载状态
      isLoading: false,
      // 控制导入组件的状态
      showExcelDialog: false,
      // 弹窗显示状态
      showRoleDialog: false,
      // 当前点击的用户ID
      currentUserId: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.detps = ListToTree(await getDepartment(), 0)
      this.queryParams.departmentId = this.detps[0].id
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    // 获取列表数据
    async getEmployeeList() {
      this.isLoading = true
      const result = await getEmplayee(this.queryParams)
      this.list = result.rows
      this.total = result.total
      this.isLoading = false
    },
    // 切换页码
    changePage(newPage) {
      this.queryParams.page = newPage
      this.getList()
    },
    // 搜索输入
    changeSearch() {
      // 清理上一次定时器
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 400)
    },
    // 导出
    async exportTable() {
      this.isLoading = true
      const result = await exportEmplayee()
      // 使用 flie-saver 保存到本地
      FileSaver.saveAs(result, '员工信息表.xlsx')
      this.isLoading = false
    },
    // 删除
    async confirmDel(id) {
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
      this.$message.success('删除成功')
    },
    // 角色按钮
    async btnRole(id) {
      const result = await getRoleList()
      this.roleList = result
      this.currentUserId = id
      const { roleIds } = await getEmplayeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    // 角色分配确定
    async btnRoleOk() {
      await assignRole({ id: this.currentUserId, roleIds: this.roleIds })
      this.$message.success('角色分配成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .right-top {
      display: flex;
      width: 100%;
      height: auto;
      justify-content: space-between;
      align-items: center;
    }
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
    .userPhoto {
      .userPhoto_span {
        display: block;
        border: 1px solid #e3e3;
        font-size: 17px;
        padding:2px;
      }
    }
  }
}

</style>
